package com.controller;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;

import com.beans.Admin;
import com.beans.AdminLog;
import com.beans.Company;
import com.beans.CompanyLog;
import com.beans.FunctionMenu;
import com.beans.Msg;
import com.beans.News;
import com.beans.Position;
import com.beans.User;
import com.beans.UserLog;
import com.service.AdminManager;
import com.service.SysManager;
import com.util.Const;
import com.vo.Page;

public class AdminController extends UniversalController {
	private AdminManager adminManager;
	private SysManager sysManager;
	
	public SysManager getSysManager() {
		return sysManager;
	}

	public void setSysManager(SysManager sysManager) {
		this.sysManager = sysManager;
	}

	public AdminManager getAdminManager() {
		return adminManager;
	}

	public void setAdminManager(AdminManager adminManager) {
		this.adminManager = adminManager;
	}

	public ModelAndView getViewHome(HttpServletRequest request,
			HttpServletResponse response) {
		return new ModelAndView("admin/Home");
	}
	//后台功能菜单树
	public ModelAndView getMenuTree(HttpServletRequest request,
			HttpServletResponse response) {
		String roller_code=request.getParameter("roller_code");
		List menuList=adminManager.getAdminDao().getMenuList(roller_code);
		String menuHtml="<ul>";
		if(menuList!=null)
		for(Map v:(List<Map>)menuList){
			String code=(String)v.get("code");
			String pCode=(String)v.get("pCode");
			String name=(String)v.get("name");
			String isLeaf=(String)v.get("isLeaf");
			String checked=(String)v.get("checked");
			if(checked==null)
				checked="";
			else
				checked="checked";
			if(code.length()==3&&"0".equals(pCode)&&isLeaf.equals("Y")){
				menuHtml+="<li><input name=\"code\" type='checkbox' value=\""+code+"\" "+checked+" >"+name+"\n";
			}else if(code.length()==3&&"0".equals(pCode)&&isLeaf.equals("N")){
				menuHtml+="<li><input name=\"code\" type='checkbox' value=\""+code+"\" "+checked+" >"+name+"<ul>";
				for(Map v1:(List<Map>)menuList){
					String code1=(String)v1.get("code");
					String pCode1=(String)v1.get("pCode");
					String name1=(String)v1.get("name");
					String isLeaf1=(String)v1.get("isLeaf");
					String checked1=(String)v1.get("checked");
					if(checked1==null)
						checked1="";
					else
						checked1="checked";
					if(code1.length()==6&&pCode1.equals(code)&&isLeaf1.equals("Y")){
						menuHtml+="<li><input name=\"code\" type='checkbox' value=\""+code1+"\" "+checked1+" >"+name1+"\n";
					}else if(code1.length()==6&&pCode1.equals(code)&&isLeaf1.equals("N")){
						menuHtml+="<li><input name=\"code\" type='checkbox' value=\""+code1+"\" "+checked1+" >"+name1+"</a><ul>";
						for(Map v2:(List<Map>)menuList){
							String code2=(String)v2.get("code");
							String pCode2=(String)v2.get("pCode");
							String name2=(String)v2.get("name");
							String isLeaf2=(String)v2.get("isLeaf");
							String checked2=(String)v2.get("checked");
							if(checked2==null)
								checked2="";
							else
								checked2="checked";
							if(code2.length()==9&&pCode2.equals(code1)&&isLeaf2.equals("Y")){
								menuHtml+="<li><input name=\"code\" type='checkbox' value=\""+code2+"\" "+checked2+" >"+name2+"\n";
							}
						}
						menuHtml+="</ul>\n";
					}
				}
				menuHtml+="</ul>\n";
			}
				
		}
		menuHtml+="</ul>";
		Map map=new HashMap();
		map.put("o", menuHtml);
		return new ModelAndView("admin/menuTree",map);
	}
	//后台角色对应的功能菜单树保存
	public ModelAndView updateMenuTree(HttpServletRequest request,
			HttpServletResponse response){
		String roller_code=request.getParameter("roller_code");
		String[] code=request.getParameterValues("code");
		try{
			adminManager.getAdminDao().updateRollerMenu(roller_code, code);
			getMessage(response, "{\"success\":true}");
		}catch(Exception e){
			e.printStackTrace();
			getMessage(response, "{\"success\":false,\"err\":\""+e.getMessage()+"\"}");
		}
		return null;
	}
	public ModelAndView getForm(HttpServletRequest request,
			HttpServletResponse response) {
		String id=request.getParameter("id");
		Map map=new HashMap();
		Admin a=new Admin();
		try{
			a=(Admin)getAdminManager().getAdminDao().findByID(Admin.class, Integer.parseInt(id));
			a.setRoller_code((String)getAdminManager().getAdminDao().getAdmin(a.getId()).get("rcode"));
		}catch(Exception e){
			e.printStackTrace();
		}
		map.put("o", a);
		return new ModelAndView("admin/form",map);
	}
	public ModelAndView getLeftMenu(HttpServletRequest request,
			HttpServletResponse response) {
		Map map = new HashMap();
		List list = null;
		Admin a=(Admin)request.getSession().getAttribute(Const.ADMIN);
		list = this.adminManager.getAdminDao().getMenuByRoller(a.getRoller_code());
		map.put("o", list);
		return new ModelAndView("admin/leftMenu",map);
	}
	public ModelAndView getLogin(HttpServletRequest request,HttpServletResponse response){
		//User u = (User) request.getSession().getAttribute("user");
		//Company c = (Company) request.getSession().getAttribute("company");
		//if (u == null && c == null) 
		//	return new ModelAndView("index");
		return new ModelAndView("admin/login");
	}
	public ModelAndView getAdminCheckLogin(HttpServletRequest request,
			HttpServletResponse response) {
//		User u = (User) request.getSession().getAttribute("user");
//		Company c = (Company) request.getSession().getAttribute("company");
		String loginName=request.getParameter("loginName");
		String pwd=request.getParameter("pwd");
		Map map=new HashMap();
//		if (u != null ||c != null) {
			String code = (String) request.getParameter("code");
			String validateCode = (String)request.getSession().getAttribute("validateCode");
			if(validateCode==null){
					map.put("loginName", loginName);
					map.put("err", "验证码过期！");
					return new ModelAndView("admin/loginError", map);
			}
			if (null == code||"".equals(code) || !code.toUpperCase().equals(validateCode.toUpperCase())) 
				{
					map.put("loginName", loginName);
					map.put("err", "验证码错误！");
					return new ModelAndView("admin/loginError", map);
				}
			Admin a=adminManager.getAdminDao().login(loginName, pwd,request.getRemoteAddr());
			if(a!=null){
				request.getSession().setAttribute("admin", a);
				request.getSession().setAttribute(Const.ADMIN_URL, adminManager.getAdminDao().getURLByRoller(a.getRoller_code()));
			}
			else{
				map.put("loginName", loginName);
				map.put("err", "账户或密码错误！");
				return new ModelAndView("admin/loginError",map);
			}
//		}
		return new ModelAndView("admin/index");
	}
	public ModelAndView loginout(HttpServletRequest request,
			HttpServletResponse response) {
		request.getSession().removeAttribute("admin");
//		request.getSession().invalidate();
		return new ModelAndView("company/loginout");
	}
	public ModelAndView getAdminPwd(HttpServletRequest request,
			HttpServletResponse response) {
		return new ModelAndView("admin/adminPwd");
	}
	public ModelAndView getUpdateAdminPwd(HttpServletRequest request,
			HttpServletResponse response) {
		Admin u=(Admin)request.getSession().getAttribute("admin");
		String oldpwd=request.getParameter("oldPwd");
		String pwd1=request.getParameter("pwd1");
		if(getAdminManager().getAdminDao().myPwd(u.getId(), oldpwd, pwd1))
			getMessage(response, "操作成功！");
		else
			getMessage(response, "操作失败！");
		return null;
	}
	public ModelAndView getUserList(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Map result = new HashMap();
		User u=new User();
		bind(request, u);
		Page page=adminManager.getUserDao().list(this.getPageNo(request), pageSize, u);
		result.put("o", page);
		return new ModelAndView("admin/userList", result);
	}
	public ModelAndView getCompanyList(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Map param = new HashMap();
		Map result = new HashMap();
		Map order = new HashMap();
		Company c = new Company();
		bind(request, c);
		if (c.getcName() != null && !"".equals(c.getcName()))
			param.put("cName", "%" + c.getcName() + "%");
		order.put("desc", "fix,registTime");
		Page page = adminManager.getCompanyDao().findPageByCriteria(
				this.getPageNo(request), pageSize, param, order, Company.class);
		result.put("o", page);
		return new ModelAndView("admin/companyList", result);
	}
	public ModelAndView getNewsList(HttpServletRequest request,
			HttpServletResponse response) throws Exception{
		Map param = new HashMap();
		Map result = new HashMap();
		News news=new News();
		String classid=request.getParameter("classid");
		String id=request.getParameter("id");
		if(classid!=null){
			String title=request.getParameter("title");
			Map order =new HashMap();
			if(title!=null&&!"".equals(title.trim()))
				param.put("title", title);
			param.put("classid", Integer.parseInt(classid));
			order.put("desc", "id");
			Page page = getUniversalManager().findPageByCriteria(this.getPageNo(request), pageSize, param,order, News.class);
			result.put("o", page);
			return new ModelAndView("admin/newsList", result);
		}
		return null;
	}
	public ModelAndView getPositionList(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Map param = new HashMap();
		Map result = new HashMap();
		Position p = new Position();
		bind(request,p);
		Page page = adminManager.getPositionDao().queryList(this.getPageNo(request), pageSize, p);
		result.put("o", page);
		return new ModelAndView("admin/positionList", result);
	}
	public ModelAndView getMsList(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Map result = new HashMap();
		Msg msg = new Msg();
		bind(request, msg);
		Page page = adminManager.getMsgDao().list(this.getPageNo(request),pageSize, msg);
		result.put("o", page);
		return new ModelAndView("admin/msgList", result);
	}
	public ModelAndView getAdminList(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Map result = new HashMap();
		Admin a=new Admin();
		bind(request, a);
		Page page=adminManager.getAdminDao().list(this.getPageNo(request), pageSize, a);
		result.put("o", page);
		return new ModelAndView("admin/adminList", result);
	}
	public ModelAndView getInsert(HttpServletRequest request,HttpServletResponse response){
		Admin a=new Admin();
		String msg="";
		try {
			bind(request,a);
			if(a.getId()==0&&adminManager.getAdminDao().findLoginName(a.getLoginName())){
				getMessage(response, "{\"success\":false,\"err\":\"此用户存在！\"}");
				return null;
			}
			if(a.getId()>0){
				Admin a2=(Admin)adminManager.getAdminDao().findByID(Admin.class,a.getId());
				a.setLoginName(a2.getLoginName());
				if(a.getPwd()==null||"".equals(a.getPwd())){
					a.setPwd(a2.getPwd());
					a.setPwd1(a2.getPwd1());
					a.setPwd2(a2.getPwd2());
					a.setPwd3(a2.getPwd3());
				}
				adminManager.getAdminDao().updateAdmin(a);
			}
			else
				adminManager.getAdminDao().insertAdmin(a);
			getMessage(response, "{\"success\":true}");
		} catch (Exception e) {
			e.printStackTrace();
			getMessage(response, "{\"success\":false,\"err\":\""+e.getMessage()+"\"}");
		}
		return null;
	}
	public ModelAndView getDelete(HttpServletRequest request,HttpServletResponse response){
		Admin a=new Admin();
		String msg="";
		String id=request.getParameter("id");
		try {
			a=(Admin)adminManager.getAdminDao().findByID(Admin.class, Integer.parseInt(id));
			if("admin".equals(a.getLoginName())){
				getMessage(response, "{\"success\":false,\"err\":\"系统默认用户不能删除！\"}");
				return null;
			}
			adminManager.getAdminDao().deleteAdmin(a);
			getMessage(response, "{\"success\":true}");
		} catch (Exception e) {
			e.printStackTrace();
			getMessage(response, "{\"success\":false,\"err\":\""+e.getMessage()+"\"}");
		}
		return null;
	}
	
	public ModelAndView getFunMenuFrame(HttpServletRequest request,
			HttpServletResponse response) {
		return new ModelAndView("admin/funMenuFrame");
	}
	public ModelAndView getFunMenuEdit(HttpServletRequest request,
			HttpServletResponse response) {
		Map map = new HashMap();
		String id = request.getParameter("id");
		FunctionMenu m = null;
		if ("0".equals(id) || "-1".equals(id))
			m = new FunctionMenu();
		else
			m = (FunctionMenu) this.sysManager.getMenuDao().findByID(FunctionMenu.class,(Serializable) id);
		map.put("o", m);
		return new ModelAndView("admin/funMenuEdit",map);
	}
	public ModelAndView getFunMenuList(HttpServletRequest request,
			HttpServletResponse response) {
		Admin a=(Admin)request.getSession().getAttribute(Const.ADMIN);
		List list=adminManager.getAdminDao().getMenuList(a.getRoller_code());
		Map m=new HashMap();
		m.put("o", list);
		return new ModelAndView("admin/funMenuList",m);
	}
	public ModelAndView getSaveFunMenu(HttpServletRequest request,HttpServletResponse response){
		FunctionMenu m=new FunctionMenu();
		String msg="";
		try {
			bind(request,m);
			FunctionMenu m2=(FunctionMenu)getUniversalManager().findByID(FunctionMenu.class, m.getCode());
			if(m.getpCode()==null||"".equals(m.getpCode()))m.setpCode("0");
			if(m2==null)
				getUniversalManager().insert(m);
			else
				getUniversalManager().update(m);
			getMessage(response, "{\"success\":true}");
		} catch (Exception e) {
			e.printStackTrace();
			getMessage(response, "{\"success\":false,\"err\":\""+e.getMessage()+"\"}");
		}
		getMessage(response, msg);
		return null;
	}
	public ModelAndView getDeleteFunMenu(HttpServletRequest request,
			HttpServletResponse response) {
		try {
			String code=request.getParameter("code");
			FunctionMenu m=(FunctionMenu)getUniversalManager().findByID(FunctionMenu.class, code);
			if(m!=null)
				getUniversalManager().delete(m);
			getMessage(response, "{\"success\":true}");
		} catch (Exception e) {
			e.printStackTrace();
			getMessage(response, "{\"success\":false,\"err\":\""+e.getMessage()+"\"}");
		}
		return null;
	}
	public ModelAndView getAdminLogList(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Map result = new HashMap();
		AdminLog log=new AdminLog();
		bind(request, log);
		Page page=adminManager.getAdminDao().getLog(this.getPageNo(request), pageSize, log);
		result.put("o", page);
		return new ModelAndView("admin/adminLogList", result);
	}
	public ModelAndView getUserLogList(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Map result = new HashMap();
		UserLog log=new UserLog();
		bind(request, log);
		Page page=adminManager.getUserDao().getLog(this.getPageNo(request), pageSize, log);
		result.put("o", page);
		return new ModelAndView("admin/userLogList", result);
	}
	public ModelAndView getCompanyLogList(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Map result = new HashMap();
		CompanyLog log=new CompanyLog();
		bind(request, log);
		Page page=adminManager.getCompanyDao().getLog(this.getPageNo(request), pageSize, log);
		result.put("o", page);
		return new ModelAndView("admin/companyLogList", result);
	}
	public ModelAndView getFunctionMenuPath(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		getMessage(response, adminManager.getAdminDao().getPath(request.getParameter("url")));
		return null;
	}
	public ModelAndView getALLURLList(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Map result = new HashMap();
		String url=request.getParameter("url");
		String function_code=request.getParameter("function_code");
		if(url==null)url="";
		if(function_code==null)function_code="";
		result.put("o", sysManager.getMenuDao().getAllURL(function_code,url));
		return new ModelAndView("admin/url", result);
	}
	public ModelAndView getUpdateFunctionURL(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Map result = new HashMap();
		String[] url=request.getParameterValues("url");
		String function_code=request.getParameter("function_code");
		if(function_code==null||url.length==0){
			getMessage(response, "{\"success\":false,\"err\":\"请选择URL！ \"}");
			return null;
		}
		adminManager.getAdminDao().getUpdateFunctionURL(function_code, url);
		getMessage(response, "{\"success\":true}");
		return null;
	}
}
